package com.github.pig.auth.component.mobile;

import com.github.pig.auth.feign.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author lengleng
 * @date 2018/1/9
 * 手机号登录配置入口
 */

/**
 * @author hj
 * @date 2018/1/9
 * 过滤器配置
 */
@Component
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private AuthenticationSuccessHandler mobileLoginSuccessHandler;
    @Autowired
    private UserService userService;


    /**
     * 定义token   MobileAuthenticationToken extends AbstractAuthenticationToken
     * 定义手机登录过滤器     MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter
     *定义校验逻辑
     * @param http
     * @throws Exception
     */


    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
        mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);  //登录成功后调用这个拦截器

        MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
        //用userService获取用户信息
        mobileAuthenticationProvider.setUserService(userService);
        //把自己写的mobileAuthenticationProvider加到AuthenticationProvider集合中去，把过滤器加到用户密码后面去
        http.authenticationProvider(mobileAuthenticationProvider)
                .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
